﻿Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Collections

Imports MySql.Data
Imports MySql.Data.MySqlClient
Imports System.Text.RegularExpressions

Public Class Main
    Public PhoneNum As String
    Public AccType As String
    Public AccID As Integer
    Public AccNum As String
    Public AccName As String
    Public InboxCount As Integer
    Public Reply As String = ""
    Public ForwardMessage As String = ""
    Public ForwardReceiver As String = ""
    Public EnableSending As Boolean = False
    Public Amount As Single
    Public ServerStatus As String = "Offline"
    Public CellInitials As DataTable

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        'SystemTimer.Enabled = True
    End Sub



    Public Sub NewMessage(ByVal message As String)
        Dim Words As String() = message.Split(New Char() {" "c})

        'Push(PhoneNum, Words)
    End Sub

    Public Function IfUser(ByVal cellnumber As String) As Boolean
        Dim value = False
        Dim Var As New Variables
        Dim User As New DataTable

        Try
            Var.Conn.Open()

            Var.Comm = New MySqlCommand("select * from tbl_users where user_num = '" & cellnumber & "'", Var.Conn)
            Var.Adapter = New MySqlDataAdapter(Var.Comm)
            Var.Adapter.Fill(User)

            Var.Conn.Close()

            If User.Rows.Count > 0 Then
                value = True
            Else
                value = False
            End If
        Catch ex As Exception
            Var.Conn.Close()
            MsgBox(ex.Message)
        End Try

        Return value
    End Function

    Public Function GetBranch(ByVal branchcode As String) As DataTable
        Dim Var As New Variables
        Dim Branch As New DataTable

        Try
            Var.Conn.Open()

            Var.Comm = New MySqlCommand("select * from tbl_contacts where contact_code = '" & branchcode & "'", Var.Conn)
            Var.Adapter = New MySqlDataAdapter(Var.Comm)
            Var.Adapter.Fill(Branch)

            Var.Conn.Close()
        Catch ex As Exception
            Var.Conn.Close()
            MsgBox(ex.Message)
        End Try

        Return Branch
    End Function

    Public Sub Push(ByVal cellnumber As String, ByVal Message As String, ByVal messdate As DateTime)
        EnableSending = False
        If IfUser(cellnumber) Then
            If Message.Contains(":") Then
                Dim Words As String() = Message.Split(New Char() {":"c})
                Dim Branch As DataTable = GetBranch(Words(0).ToUpper)
                If Branch.Rows.Count > 0 Then
                    SaveReport(Branch.Rows(0)("contact_num"), Words(1), messdate)
                Else
                    EnableSending = True
                    Reply = "Branch not found.. Please check!"
                End If

            End If
        Else
            SaveReport(cellnumber, Message, messdate)
        End If

    End Sub

    Public Sub SaveReport(ByVal cellnumber As String, ByVal Message As String, ByVal messdate As DateTime)
        Dim Words As String() = Message.Split(New Char() {" "c})

        ForwardMessage = ""
        EnableSending = True
        Dim Command As String = Words(0)

        cellnumber = cellnumber.Replace("+63", "0")

        Dim Var As New Variables

        Dim Branch As New DataTable
        Dim BCount As New DataTable

        Try
            Var.Conn.Open()

            Var.Comm = New MySqlCommand("select * from tbl_contacts where contact_num = '" & cellnumber & "'", Var.Conn)
            Var.Adapter = New MySqlDataAdapter(Var.Comm)
            Var.Adapter.Fill(Branch)

            Var.Conn.Close()

            If Branch.Rows.Count = 0 Then
                Exit Sub
            End If
        Catch ex As Exception
            Var.Conn.Close()
        End Try

        Try
            Var.Conn.Open()

            Var.Comm = New MySqlCommand("insert into tbl_log(contact_name, contact_num, log_message, log_date) values (@contact_name, @contact_num, @log_message, @log_date)", Var.Conn)
            Var.Comm.CommandType = CommandType.Text
            Var.Comm.Parameters.Add(New MySqlParameter("@contact_name", Branch.Rows(0)("contact_name")))
            Var.Comm.Parameters.Add(New MySqlParameter("@log_message", Message))
            Var.Comm.Parameters.Add(New MySqlParameter("@log_date", messdate.ToString("hh:mm tt MMMM dd, yyyy")))
            Var.Comm.Parameters.Add(New MySqlParameter("@contact_num", Branch.Rows(0)("contact_num")))
            Var.Comm.ExecuteNonQuery()

            Var.Conn.Close()
        Catch ex As Exception
            Var.Conn.Close()
        End Try

        If Command.ToLower.Contains("remarks") Or Command.ToLower.Contains("remark") Then
            Dim Remarks As String = ""
            If Words.Count > 1 Then
                For x = 1 To Words.Count - 1
                    Remarks += Words(x) & " "
                Next
            Else
                Exit Sub
            End If
            Try
                Var.Conn.Open()

                Var.Comm = New MySqlCommand("insert into tbl_remarks(remarks,contact_id,remarks_date) values (@remarks, @contact_id, @remarks_date)", Var.Conn)
                Var.Comm.CommandType = CommandType.Text
                Var.Comm.Parameters.Add(New MySqlParameter("@remarks", Remarks))
                Var.Comm.Parameters.Add(New MySqlParameter("@contact_id", Branch.Rows(0)("contact_id")))
                Var.Comm.Parameters.Add(New MySqlParameter("@remarks_date", messdate.ToString("MMMM dd, yyyy")))
                Var.Comm.ExecuteNonQuery()

                Var.Conn.Close()
            Catch ex As Exception
                Var.Conn.Close()

            End Try

            If My.Settings.RemarksReply = True Then
                JSMS.SendQueue.Rows.Add(cellnumber, My.Settings.RemarksMessage)
            End If
            Exit Sub
        End If

        Dim reportSaved = False

        Try
            For x = 0 To Words.Count - 1
                Dim codeholder As String = Words(x).Substring(0, 2)
                Dim code As String = codeholder.Trim()
                Dim value As String = Words(x).Replace(code, "")

                If code.Length <> 2 Then
                    Continue For
                End If

                If value.Length = 0 Then
                    Continue For
                End If

                Dim searchcount As New DataTable
                Dim data As New DataTable
                Try
                    Var.Conn.Open()

                    Var.Comm = New MySqlCommand("select * from tbl_codes where code = '" & code.ToUpper & "'", Var.Conn)
                    Var.Adapter = New MySqlDataAdapter(Var.Comm)
                    Var.Adapter.Fill(data)

                    Var.Conn.Close()
                Catch ex As Exception
                    Var.Conn.Close()
                End Try

                If data.Rows.Count > 0 Then
                    Try
                        Var.Conn.Open()

                        Var.Comm = New MySqlCommand("delete from tbl_values where contact_id = @contact_id and code_id = @code_id and report_date = @report_date", Var.Conn)
                        Var.Comm.CommandType = CommandType.Text
                        Var.Comm.Parameters.Add(New MySqlParameter("@contact_id", Branch.Rows(0)("contact_id")))
                        Var.Comm.Parameters.Add(New MySqlParameter("@code_id", data.Rows(0)("code_id")))
                        Var.Comm.Parameters.Add(New MySqlParameter("@report_date", messdate.ToString("MMMM dd, yyyy")))
                        Var.Comm.ExecuteNonQuery()

                        Var.Conn.Close()
                    Catch ex As Exception
                        Var.Conn.Close()
                    End Try

                    Try
                        Var.Conn.Open()

                        Var.Comm = New MySqlCommand("insert into tbl_values(contact_id, code_id, value, report_date) values(@contact_id,@code_id,@value,@report_date)", Var.Conn)
                        Var.Comm.CommandType = CommandType.Text
                        Var.Comm.Parameters.Add(New MySqlParameter("@contact_id", Branch.Rows(0)("contact_id")))
                        Var.Comm.Parameters.Add(New MySqlParameter("@code_id", data.Rows(0)("code_id")))
                        Var.Comm.Parameters.Add(New MySqlParameter("@value", value))
                        Var.Comm.Parameters.Add(New MySqlParameter("@report_date", messdate.ToString("MMMM dd, yyyy")))
                        Var.Comm.ExecuteNonQuery()

                        Var.Conn.Close()

                        reportSaved = True

                    Catch ex As Exception
                        Var.Conn.Close()
                    End Try


                End If


            Next

            If reportSaved = True Then
                If My.Settings.ReportReply = True Then
                    JSMS.SendQueue.Rows.Add(cellnumber, My.Settings.ReportMessage)
                End If
            Else
                Dim formholder As New NewMessageAlert
                formholder.Name = cellnumber
                formholder.TextBox1.Text = cellnumber & "(" & Branch.Rows(0)("contact_name") & "): " & Message
                formholder.MdiParent = Me
                formholder.Show()
                formholder.BringToFront()
                formholder.TextBox2.Focus()
            End If
        Catch ex As Exception

        End Try

    End Sub

    Public Sub AddLine(ByVal line As String)
        'RadTextBox2.Text += ">" & line & vbCrLf
    End Sub

    Public Sub RefreshInventoryList()
        Dim Inventory As New Inventory
        'RadGridView1.DataSource = Inventory.GetAllItems
    End Sub

    Public Function InConcat(ByVal cell As String) As Boolean
        Dim Value = False
        For x = 0 To JSMS.concat.Rows.Count - 1
            If JSMS.concat.Rows(x).Cells("tempSender").Value = cell Then
                Value = True
            End If
        Next
        Return Value
    End Function

    Public Sub Processor()
        'Dim TPool As System.Threading.ThreadPool
        
        Do While JSMS.Inbox.Rows.Count > 0
            Try
                Dim Cell As String = JSMS.Inbox.Rows(0).Cells("sender").Value
                Dim Message As String = JSMS.Inbox.Rows(0).Cells("message").Value

                Dim MessTime As DateTime
                'MsgBox(Message.Count)

                If JSMS.Inbox.Rows(0).Cells("time").Value.ToString.Contains("+") Then
                    Dim messtimeholder = JSMS.Inbox.Rows(0).Cells("time").Value.ToString.Replace(" +", "+")
                    Dim messtimeslice As String() = messtimeholder.Split(New Char() {"+"c})
                    MessTime = messtimeslice(0)
                Else
                    MessTime = JSMS.Inbox.Rows(0).Cells("time").Value
                End If

                JSMS.Inbox.Rows.RemoveAt(0)

                If Message.Contains("@") Then
                    Dim words As String() = Message.Split(New Char() {"@"c})
                    If InConcat(Cell) = False Then
                        JSMS.concat.Rows.Add(Cell, words(words.Count - 1), MessTime)
                    Else
                        For x = 0 To JSMS.concat.Rows.Count - 1
                            If JSMS.concat.Rows(x).Cells("tempSender").Value = Cell Then
                                JSMS.concat.Rows(x).Cells("tempMessage").Value &= words(words.Count - 1)
                            End If
                        Next

                        If Message.Length <> 160 Then
                            Dim concatIndex = 0
                            For x = 0 To JSMS.concat.Rows.Count - 1
                                If JSMS.concat.Rows(x).Cells("tempSender").Value = Cell Then
                                    Dim s1 = JSMS.concat.Rows(x).Cells("tempSender").Value
                                    Dim s2 = JSMS.concat.Rows(x).Cells("tempMessage").Value
                                    Dim s3 = JSMS.concat.Rows(x).Cells("tempTime").Value
                                    JSMS.Inbox.Rows.Add(s1, s2, s3)
                                    concatIndex = x
                                End If
                            Next
                            JSMS.concat.Rows.RemoveAt(concatIndex)
                        End If
                    End If

                    Exit Sub
                End If

                Dim notinspamguard = False

                If JSMS.SpamGuard.Rows.Count > 0 Then
                    For x = 0 To JSMS.SpamGuard.Rows.Count - 1
                        If JSMS.SpamGuard.Rows(x).Cells("sendernumber").Value = Cell And JSMS.SpamGuard.Rows(x).Cells("sendermessage").Value = Message Then
                            JSMS.SendQueue.Rows.Add(Cell, "Warning. Identical transaction not allowed. Please try another transaction.")
                            Exit Sub
                        Else
                            notinspamguard = True
                        End If
                    Next
                Else
                    If ServerStatus = "Online" Then
                        JSMS.SpamGuard.Rows.Add(Cell, Message)
                    End If
                End If

                If notinspamguard = True Then
                    If ServerStatus = "Online" Then
                        JSMS.SpamGuard.Rows.Add(Cell, Message)
                    End If
                End If



                'ThreadPool.QueueUserWorkItem(New WaitCallback(Sub() Push(Cell, Message)))
                Push(Cell, Message, MessTime)

            Catch ex As Exception

            End Try


        Loop

        'SystemTimer.Enabled = True
    End Sub

    Public Sub Loader()
        RefreshInventoryList()
    End Sub

    '===========================================================================================================

    Private Sub RadMenuItem10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        NewProduct.ShowDialog()
    End Sub


    Private Sub Main_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        Try
            WaitingBar.StopWaiting()
            Application.Exit()
        Catch ex As Exception

        End Try
    End Sub

    Private Sub Main_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.Text += " (" & My.Settings.Subscription.ToUpper & " EDITION)"
    End Sub

    Public SetupComplete As Boolean = True

    Private Sub Main_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
        If My.Settings.FirstTimeUse = True Then
            SetupComplete = False
            SetupWizard.ShowDialog()
        End If

        If SetupComplete = False Then
            Me.Close()
        Else
            If My.Settings.EnabledSecurity = True Then
                Splash.ShowDialog()
                RadPanorama1.Visible = True
                RadStatusStrip1.Visible = True
            End If

        End If

        If My.Settings.build3rev2patch = False Then
            Dim var As New Variables
            Try
                var.Conn.Open()

                Dim comm = New MySqlCommand("ALTER TABLE `hermes`.`tbl_codes` CHANGE COLUMN `code_order` `code_order` BIGINT NOT NULL", var.Conn)
                comm.ExecuteNonQuery()
                comm = New MySqlCommand("ALTER TABLE `hermes`.`tbl_values` CHANGE COLUMN `value` `value` VARCHAR(100) NULL DEFAULT NULL", var.Conn)
                comm.ExecuteNonQuery()
                var.Conn.Close()
                My.Settings.build3rev2patch = True
                My.Settings.Save()
            Catch ex As Exception
                var.Conn.Close()
            End Try



        End If

        Me.Refresh()
        WaitingBar.StartWaiting()
        Status.Text = "Ready!"

    End Sub

    '=========================================================================


    Private Sub UsersToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UsersToolStripMenuItem.Click
        Users.MdiParent = Me
        Users.Show()
        Users.BringToFront()
    End Sub

    Private Sub ItemToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ItemToolStripMenuItem.Click
        AllProducts.MdiParent = Me
        AllProducts.Show()
        AllProducts.BringToFront()
    End Sub

    Private Sub LockApplicationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LockApplicationToolStripMenuItem.Click
        Splash.ShowDialog()
    End Sub


    Public Sub Enlist()

    End Sub

    Public Sub UpdateSales()

    End Sub

    Public Sub LoadSales()

    End Sub

    Private Sub RadTextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadTextBox1.TextChanged
        Dim TotalAmount As Integer = 0
        For x = 0 To RadGridView1.Rows.Count - 1
            Dim todayDate As Date = RadGridView1.Rows(x).Cells("sales_date").Value
            If (todayDate.ToString("MMMM dd, yyyy") = RadDateTimePicker1.Text) And (RadGridView1.Rows(x).Cells("acc_num").Value.ToString().Contains(RadTextBox1.Text) Or RadGridView1.Rows(x).Cells("acc_name").Value.ToString().Contains(RadTextBox1.Text)) Then
                RadGridView1.Rows(x).IsVisible = True
                TotalAmount += RadGridView1.Rows(x).Cells("sales_amount").Value
            Else
                RadGridView1.Rows(x).IsVisible = False
            End If
        Next

        Label10.Text = TotalAmount.ToString("0.00")
    End Sub

    Private Sub ViewCollectionsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub CustomersToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CustomersToolStripMenuItem.Click
        Customers.MdiParent = Me
        Customers.Show()
        Customers.BringToFront()
    End Sub

    Private Sub SalesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SalesToolStripMenuItem.Click
        ViewSales.MdiParent = Me
        ViewSales.Show()
        ViewSales.BringToFront()
    End Sub

    Private Sub CollectionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CollectionToolStripMenuItem.Click
        ViewCollections.MdiParent = Me
        ViewCollections.Show()
        ViewCollections.BringToFront()
    End Sub

    Private Sub RadTileElement1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadTileElement1.Click
        JSMS.MdiParent = Me
        JSMS.Show()
        JSMS.BringToFront()
    End Sub

    Private Sub RadTileElement2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadTileElement2.Click
        BroadcastSMS.MdiParent = Me
        BroadcastSMS.Show()
        BroadcastSMS.BringToFront()
    End Sub

    Private Sub RadTileElement3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadTileElement3.Click
        AltUser.MdiParent = Me
        AltUser.Show()
        AltUser.BringToFront()
    End Sub

    Private Sub RadTileElement4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadTileElement4.Click
        Contacts.MdiParent = Me
        Contacts.Show()
        Contacts.BringToFront()
    End Sub

    Private Sub RadTileElement5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadTileElement5.Click
        TextCodes.MdiParent = Me
        TextCodes.Show()
        TextCodes.BringToFront()
    End Sub

    Private Sub RadTileElement6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadTileElement6.Click
        MessageLogs.MdiParent = Me
        MessageLogs.Show()
        MessageLogs.BringToFront()
    End Sub

    Private Sub RadTileElement7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadTileElement7.Click
        Reports.MdiParent = Me
        Reports.Show()
        Reports.BringToFront()
    End Sub

    Private Sub RadTileElement8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadTileElement8.Click
        Settings.MdiParent = Me
        Settings.Show()
        Settings.BringToFront()
    End Sub

    Private Sub RadTileElement9_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadTileElement9.Click
        AboutHermes.ShowDialog()
    End Sub
End Class
